package com.shqcjd.preinstallmobile.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.AbnormalBean;
import com.shqcjd.preinstallmobile.model.pojo.EquipmentAbnormalBean;
import com.shqcjd.preinstallmobile.model.pojo.ImgBean;
import com.shqcjd.preinstallmobile.model.pojo.UploadException;
import com.shqcjd.preinstallmobile.ui.adapter.EquipmentAbnormalAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.AlbumUtils;
import com.shqcjd.preinstallmobile.util.MyGlideEngine;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.widget.AbnormalGroupDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class EquipmentAbnormalActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.rv_equipment_abnormal)
    RecyclerView rvEquipmentAbnormal;
    private EquipmentAbnormalActivity context;
    private EquipmentAbnormalAdapter equipmentAbnormalAdapter;
    public List<RadioGroup> radioGroupList = new ArrayList<>();
    private int eId, tId;
    private AbnormalGroupDialog abnormalDialog;
    private final int IMAGE_FILE_RESULT_CODE = 2;
    private View notDataView;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_equipment_abnormal;
    }

    @Override
    public void init() {
        super.init();
        eId = getIntent().getIntExtra("eId", 1);
        tId = getIntent().getIntExtra("tId", 1);
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvIncludeTitle.setText("设备组巡检");
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvEquipmentAbnormal.getParent(), false);

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getData();
    }

    private void getData() {
        ApiService.equipmentAbnormalHttp(tId, eId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentAbnormalBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentAbnormalBean> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        rvEquipmentAbnormal.setLayoutManager(new LinearLayoutManager(context));
                        equipmentAbnormalAdapter = new EquipmentAbnormalAdapter(responseData.data.equipment_part, context, responseData.data.equipment_id);
                        rvEquipmentAbnormal.setAdapter(equipmentAbnormalAdapter);

                        if (responseData.data.equipment_part.size() > 0) {
                            equipmentAbnormalAdapter.setNewData(responseData.data.equipment_part);
                        } else {
                            equipmentAbnormalAdapter.setNewData(null);
                            equipmentAbnormalAdapter.setEmptyView(notDataView);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void isCheckAll(){
        for(int i=0; i<radioGroupList.size(); i++){
            RadioGroup radioGroup = radioGroupList.get(i);
            RadioButton rb1 = (RadioButton)radioGroup.getChildAt(1);
            RadioButton rb2 = (RadioButton)radioGroup.getChildAt(3);
            if(!rb1.isChecked()&&!rb2.isChecked()){
                return ;
            }
        }
        finish();
    }


    public void putCheckResultHttp(int epId, String value, int status, int eId) {
        Map<String, String> map = new HashMap<>();
        map.put("task_id", tId+"");
        map.put("equipment_part_item_id", eId+"");
        map.put("value", value);
        map.put("status", status+"");
        map.put("equipment_id", epId+"");

        ApiService.putCheckResultHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> responseData) {
                        if(responseData.retCode!=10000){
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }else{
                            if(status==-1){
                                getAbnormalInfoHttp(tId, epId, eId, value, responseData.data);
                            }else{
                                context.isCheckAll();
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void getAbnormalInfoHttp(int task_id, int equipment_id, int equipment_part_item_id, String value, int prId) {
        ApiService.getAbnormalInfo(task_id, equipment_id, equipment_part_item_id, value)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<AbnormalBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<AbnormalBean> responseData) {
                        if (responseData.retCode == 10000) {
                            List<ImgBean> list = new ArrayList<>();
                            for(int i=0; i<responseData.data.imgs.size(); i++){
                                list.add(new ImgBean(responseData.data.imgs.get(i), false));
                            }
                            showUploadDialog(prId, responseData.data.exception_description, list, responseData.data.solution_description);
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    /**
     * 显示异常图片上传对话框
     */
    private void showUploadDialog(Integer prid, String str, List<ImgBean> img, String solution) {
        if(abnormalDialog==null){
            abnormalDialog = new AbnormalGroupDialog(context);
            abnormalDialog.setOnBtnClickListener(new AbnormalGroupDialog.OnBtnClickListener() {
                @Override
                public void onBtnClick(View view, List<String> mList) {
                    if (mList.size() > 0) {
                        loadMultiFile(mList,prid);
                    }

                }
            });
            abnormalDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    abnormalDialog.clearDialogView();
                    isCheckAll();
                }
            });
        }
        if(!abnormalDialog.isShowing()){
            abnormalDialog.show();
            abnormalDialog.setAbnormalInfo(str, img, solution);
        }
    }

    /**
     * 上传多图
     * @param mList
     * @param prid
     */
    private void loadMultiFile(List<String> mList, Integer prid) {
        List<File> files = new ArrayList<>();
        for (String uri : mList) {
            files.add(new File(uri));
        }
        ApiService.uploadMultiImg(files)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<String>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("上传图片中");
                    }

                    @Override
                    public void _onNext(ResponseData<List<String>> retData) {
                        if (retData.retCode == 10000) {
                            putExceptionInfo(retData.data,prid);
                        } else {
                            ToastUtils.showShort(context,"上传失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(EquipmentAbnormalActivity.this)
                                    .choose(MimeType.allOf()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(6) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    /**
     * 添加或修改巡检异常描述
     * @param data
     * @param prid
     */
    private void putExceptionInfo(List<String> data, Integer prid) {
        String info = abnormalDialog.et_dialog_abnormal.getText().toString();
        UploadException uploadException = new UploadException();
        uploadException.patrol_record_id=prid;
        uploadException.info = info;
        uploadException.imgs = data;
        String json = new Gson().toJson(uploadException);

        ApiService.putCheckException(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在上传异常信息");
                    }

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData.retCode == 10000) {
                            abnormalDialog.dismiss();
                            ToastUtils.showShort(context,"提交成功");
                        } else {
                            ToastUtils.showShort(context,"提交信息失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        abnormalDialog.addPic(albumStringPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
